from rest_framework.viewsets import ModelViewSet, GenericViewSet
from rest_framework.response import Response
from django.http import HttpResponse
from rest_framework import mixins
from product.models import ProductType, Product, ProductBanner
from product.serializers import ProductTypeSerializer, ProductSerializer, ProductBannerSerializer
from django.utils.decorators import method_decorator
from libs.utils.decorator import request_log
from django.core.exceptions import ObjectDoesNotExist
from libs.utils.response import OBJECT_NOT_FOUND, API_SUCCESS
import xlwt
from io import BytesIO
from rest_framework.decorators import api_view
import logging

logger = logging.getLogger("BlueDot")

class ProductTypeView(ModelViewSet):
    queryset = ProductType.objects.all()
    serializer_class = ProductTypeSerializer

class ProductBannerView(ModelViewSet):
    queryset = ProductBanner.objects.all()
    serializer_class = ProductBannerSerializer


class ProductView(ModelViewSet):
    queryset = Product.objects.all()
    serializer_class = ProductSerializer

    # 使用filter过滤
    my_filter_fields = ('name', 'type', 'num', 'min_price', 'max_price', 'min_ctime', 'max_ctime', 'min_stock', 'max_stock', 'min_sales', 'max_sales')

    # Pagination过滤
    page_fields = ('page', 'per_page')

    ## 获取筛选参数
    def get_kwargs_for_filtering(self):
        filtering_kwargs = {}
        for field in self.my_filter_fields:
            field_value = self.request.query_params.get(field)
            if field_value:
                if field.startswith("min_"):
                    newField = field.removeprefix("min_") + "__gte"
                    filtering_kwargs[newField] = int(field_value)
                elif field.startswith("max_"):
                    newField = field.removeprefix("max_") + "__lte"
                    filtering_kwargs[newField] = int(field_value)
                elif field == 'name':
                    filtering_kwargs["name__contains"] = field_value
                else:
                    filtering_kwargs[field] = field_value
        return filtering_kwargs

    # 获取分页参数
    def get_kwargs_for_page(self):
        page_kwargs = {
            "page": 1,  # 默认页码
            "per_page": 15  # 默认每页数量
        }

        for field in self.page_fields:
            field_value = self.request.query_params.get(field)
            if field_value:
                page_kwargs[field] = int(field_value)

        return page_kwargs

    def list(self, request):
        """
        商品列表
        """
        filtering_kwargs = self.get_kwargs_for_filtering()

        if filtering_kwargs:
            self.queryset = self.queryset.filter(**filtering_kwargs)

        pagination_queryset = self.paginate_queryset(self.queryset)
        serializer = self.get_serializer(pagination_queryset, many=True)
        resp = self.get_paginated_response(serializer.data)

        return resp

"""
API操作视图
"""
@method_decorator(request_log(level='INFO'))
def batch_edit(request):
    """
    批量编辑商品(上下架)
    :param request:
    :return:
    """
    ids = request.POST["ids"]
    status = request.POST["status"]

    try:
        # for id in ids.split(","):
        print("批量更新")
    except ObjectDoesNotExist:
        return Response(OBJECT_NOT_FOUND)

    return Response(API_SUCCESS)


class ExportProductView(mixins.ListModelMixin, GenericViewSet):
    queryset = Product.objects.all()
    serializer_class = ProductSerializer

    # 使用filter过滤
    my_filter_fields = (
    'name', 'type', 'num', 'min_price', 'max_price', 'min_ctime', 'max_ctime', 'min_stock', 'max_stock', 'min_sales',
    'max_sales')

    # Pagination过滤
    page_fields = ('page', 'per_page')

    ## 获取筛选参数
    def get_kwargs_for_filtering(self):
        filtering_kwargs = {}
        for field in self.my_filter_fields:
            field_value = self.request.query_params.get(field)
            if field_value:
                if field.startswith("min_"):
                    newField = field.removeprefix("min_") + "__gte"
                    filtering_kwargs[newField] = int(field_value)
                elif field.startswith("max_"):
                    newField = field.removeprefix("max_") + "__lte"
                    filtering_kwargs[newField] = int(field_value)
                elif field == 'name':
                    filtering_kwargs["name__contains"] = field_value
                else:
                    filtering_kwargs[field] = field_value
        return filtering_kwargs

    def list(self, request):
        """
        导出商品列表
        """
        filtering_kwargs = self.get_kwargs_for_filtering()

        if filtering_kwargs:
            self.queryset = self.queryset.filter(**filtering_kwargs)

        serializer = self.get_serializer(self.queryset, many=True)

        response = HttpResponse(content_type='application/vnd.ms-excel')
        response['Content-Disposition'] = 'attachment;filename=product.xls'

        if serializer.data:
            ws = xlwt.Workbook(encoding='utf-8')
            # 添加第一页数据
            w = ws.add_sheet('sheet1')

            # 写入表头
            w.write(0, 0, u'商品ID')
            w.write(0, 1, u'商品名称')
            w.write(0, 2, u'商品类型')
            w.write(0, 3, u'商品积分单价')
            w.write(0, 4, u'缩略图地址')
            w.write(0, 5, u'状态')
            w.write(0, 6, u'库存')
            w.write(0, 7, u'新增时间')

            excel_row = 1
            for obj in serializer.data:
                w.write(excel_row, 0, obj.get('id'))
                w.write(excel_row, 1, obj.get('name'))
                w.write(excel_row, 2, obj.get('type'))
                w.write(excel_row, 3, obj.get('price'))
                w.write(excel_row, 4, obj.get('thumb'))
                w.write(excel_row, 5, obj.get('status'))
                w.write(excel_row, 6, obj.get('stock'))
                w.write(excel_row, 7, obj.get('ctime'))
                excel_row += 1

            # 写出到IO
            output = BytesIO()
            ws.save(output)
            # 重新定位到开始
            output.seek(0)
            response.write(output.getvalue())


        return response
